import Cocoa
import FlutterMacOS

class MainFlutterWindow: NSWindow {
  // 窗口大小保存的Key
  private let windowFrameKey = "MainWindowFrame"

  override func awakeFromNib() {
    let flutterViewController = FlutterViewController()
    let windowFrame = self.frame
    self.contentViewController = flutterViewController
    self.setFrame(windowFrame, display: true)

    RegisterGeneratedPlugins(registry: flutterViewController)

    super.awakeFromNib()

    // 恢复上次保存的窗口大小和位置
    restoreWindowFrame()

    // 监听窗口大小变化，自动保存
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(windowDidResize),
      name: NSWindow.didResizeNotification,
      object: self
    )

    // 监听窗口移动，自动保存位置
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(windowDidMove),
      name: NSWindow.didMoveNotification,
      object: self
    )
  }

  // 恢复窗口大小和位置
  private func restoreWindowFrame() {
    if let frameString = UserDefaults.standard.string(forKey: windowFrameKey) {
      let frame = NSRectFromString(frameString)
      // 确保窗口在屏幕可见区域内
      if !frame.isEmpty {
        self.setFrame(frame, display: true)
      }
    }
  }

  // 保存窗口大小和位置
  private func saveWindowFrame() {
    let frameString = NSStringFromRect(self.frame)
    UserDefaults.standard.set(frameString, forKey: windowFrameKey)
  }

  // 窗口大小改变时保存
  @objc private func windowDidResize() {
    saveWindowFrame()
  }

  // 窗口位置改变时保存
  @objc private func windowDidMove() {
    saveWindowFrame()
  }

  deinit {
    // 移除通知监听
    NotificationCenter.default.removeObserver(self)
  }
}
